import axios from "axios";
import type {AxiosResponse} from "axios";

import {configureInterceptors, StatusCode} from "@/api";
import type {JsonResult} from "@/api";

const instance = axios.create({
    baseURL: "/v1/user"
});

configureInterceptors(instance);

export interface User {
    readonly id?: number | string,
    username: string,
    password?: string,
    roleId: number
}

const users = new Map<number, Promise<AxiosResponse<JsonResult<User>>>>();

export default {
    login: (username: string, password: string) => instance.post<JsonResult<{token: string, info: User}>>("/login", { username, password }),
    myInfo: () => instance.get<JsonResult<User>>("/myInfo"),
    get: (id: number, reload: boolean) => {
        let promise = users.get(id);
        if(reload || !promise) {
            promise = instance.get<JsonResult<User>>(`/get/${id}`);
            promise.then((resp) => {
                if(resp.data.code !== StatusCode.SUCCESS) {
                    users.delete(id);
                }
            }).catch(() => users.delete(id));

            users.set(id, promise);
        }

        return promise;
    }
}
